import { WeaLocaleProvider, WeaTools } from "ecCom";
import { action, observable, toJS } from "mobx";
import querystring from 'querystring';
import fillin from "../../apis/fillin";
import app from '../../apis/app';
import { propsComToViewCom } from "../../components/designer/form/component";
import { isAddress, isAttachment, isBrowserHrm, isBoardElement, isDataTable, isLayout, isMobileCom, isNormal, isOptional, isPicture, isSignature, isVisible, isWrapper, needValid } from "../../components/designer/form/component/typeof";
import EdcForm from '../../components/designer/form/script-code/edc-form';
import EE from "../../components/designer/form/script-code/edc-form/event";
import { eventTypes } from '../../constants/events';
import { getTheme } from "../../components/designer/form/theme";
import ThirdParty from "../../components/designer/form/view/third-party";
import { comsType, editType, resultTypes, ruleTypes, viewTypes } from "../../constants/form";
import { langTypes } from '../../constants/lang';
import isMobile, { isEMobile7, isDingTalk, isWXWork } from "../../utils/mobileDetect";
import { emit } from '../../utils/emit';
import getPageUrlParams from '../../utils/getUrlParams';
import { setComsValFromUrlParams } from '../../utils/setComsValFromUrlParams';

const { formatMultiLang, getUserLanguage, getLocaleLabelByLang } = WeaLocaleProvider;
const getLocaleLabel = WeaLocaleProvider.getLocaleLabel.bind(this, 'edc');

const { DOMLOAD, FIELDVALUECHANGE, ONSUBMIT, ONBEFORESUBMIT } = eventTypes;
const { FIELD, JUMP } = ruleTypes;
const { PC, MOBILE, MOBILE_WX, READONLY } = viewTypes;
const { FORM_HEADER, FORM_FOOTER, FOOTER } = comsType;
const { DIRECT_EDIT, CONFIRM_EDIT } = editType;
const defaultTheme = getTheme();

export default class FormViewStore {
  @observable shortkey = '';
  @observable formHeader = null;
  @observable formFooter = null;
  @observable footer = null;
  @observable components = null;
  @observable isInit = false;
  @observable errorCom = null;
  @observable submiting = false;
  @observable success = false;
  @observable error = null;
  @observable noEdit = false;
  @observable viewType = isMobile() ? MOBILE : PC;
  @observable formdata = {};
  @observable rightLevel = 0;
  @observable oauthKey = null;
  @observable oauthError = null;
  @observable theme = defaultTheme;
  @observable isEdit = false;
  @observable successMessage = '';
  @observable editConfirm = false;
  @observable editData = null;
  @observable codeBlock = null;
  @observable isOAUser = false;
  @observable appid = '';
  @observable EMobileLangType = '';
  @observable resultPageStatus = '';
  @observable submitCount = '';
  @observable fillinEnable = '';
  @observable editBaseInfo = null;
  @observable systemDefaultLang = null;
  @observable readOnlyBaseData = '';
  @observable repairDate = '';
  @observable timeLimit = null;
  @observable isShowRepairList = false;
  @observable isShowRepairTitle = false;
  @observable code = '';
  @observable browserInfo = {
    href: location.href,
    browserLanguage: navigator.browserLanguage || navigator.language
  };
  @observable joinCube = {
    formmodeId: '',
    isSetCategory: true
  }; // 关联建模模块
  @observable emOpenUrl = ''; // em的location地址
  //重置表单页面
  @action reset = () => {
    if (this.repairDate) {
      this.repairDate = '';
      this.success = false;
      this.init(this.shortkey);
    }
  }

  @action init = shortkey => new Promise((resolve, reject) => {
    // 单点
    this.singleSignOn().then(() => {
      if (!shortkey) return;
      this.isInit = true;
      this.shortkey = shortkey;
      this.theme = getTheme('default');

      fillin.check(shortkey, this.oauthKey).then(res => {
        if (this.repairDate) {
          res.code = resultTypes.NORMAL;
          this.viewType = isMobile() ? MOBILE : PC;
          this.handleNew();
        }
        this.code = res.code;
        this.isShowRepairTitle = res.makeUp;
        this.emOpenUrl = res.emOpenUrl;
        const setData = res => {
          this.appid = res.appid || '';
          this.rightLevel = res.rightLevel || '';
          this.isInit = false;
        }

        if (res.code === resultTypes.ERROR) {
          this.thridPartyInit()
            .then(() => this.initClientLanguage(res.isOAUser))
            .then(r => {
              this.error = {
                api_errormsg: res.errorMsg
              };

              setData(res);
            });

          resolve();
          return;
        } else if (res.code === resultTypes.NORIGHT || res.code === resultTypes.EXAMINING) {
          this.thridPartyInit()
            .then(() => this.initClientLanguage(res.isOAUser))
            .then(r => {
              this.noRight = res;

              this.resultPageStatus = res.code;
              setData(res);
            });

          resolve();
          return;
        }

        if (res.code === resultTypes.NOEDIT) {
          this.noEdit = res;
        }

        this.appid = res.appid || '';
        const { isOAUser, rightLevel } = res;

        this.error = null;
        this.rightLevel = rightLevel;

        const makeUpKey = this.repairDate ? true : false;
        const pageParams = getPageUrlParams();

        Promise.all([
          fillin.getPageInfo(shortkey, this.oauthKey, makeUpKey, JSON.stringify(pageParams)),
          fillin.getRules(shortkey),
          this.thridPartyInit().then(() => this.initClientLanguage(res.isOAUser)),
        ]).then(([res, rules]) => {
          let coms = res.comps;

          coms = setComsValFromUrlParams(coms);

          if (!isOAUser) {
            coms = coms.filter(com => !isBrowserHrm(com));
            coms = coms.filter(com => !isBoardElement(com));
          }

          if (res.sysData) {
            const { createdate, creatorId } = res.sysData;

            this.editBaseInfo = { createdate, creatorId };
          }

          if (res.timeLimit) {
            this.timeLimit = JSON.parse(res.timeLimit);
          }

          if (res.codeBlock) {
            this.codeBlock = JSON.parse(res.codeBlock);
          }

          if (res.style) {
            const style = JSON.parse(res.style);
            style && (this.theme = style);

            const background = style.background;
            if (background && background.type == 0) {
              this.addbgStyle(background.css);
            }
          }
          const _rules = type => rules.filter(r => type === r.type);
          const components = this.convertToViewComponent(coms);
          const comMaps = {};

          components.forEach(com => {
            comMaps[com.uuid] = com;
          });

          this.successMessage = res.edcLabelTips['SUBMITFORM_TIP'];
          this.error = null;
          this.isInit = false;
          this.rules = _rules(FIELD)
          this.formHeader = coms.find(com => com.type === FORM_HEADER);
          this.formFooter = coms.find(com => com.type === FORM_FOOTER);
          this.footer = coms.find(com => com.type === FOOTER);

          this.rules.forEach(({
            target
          }) => {
            target.split(',').forEach(tId => {
              const com = this.getComponent(tId, components);

              com.visible = false;
            });
          });

          this.components = components.filter(com => {
            if (!com.pid) return true;

            return !isDataTable(comMaps[com.pid]);
          });
          this.jumpRule = _rules(JUMP);

          const isEdit = res.isEdit;
          if (isEdit === CONFIRM_EDIT || isEdit === DIRECT_EDIT) {
            this.editData = res.data;
            if (isEdit === CONFIRM_EDIT) {
              this.editConfirm = true;
            }
            if (isEdit === DIRECT_EDIT) {
              this.handleEdit();
            }
          } else {
            this.triggerAllFieldRules();
          }

          document.title = formatMultiLang(this.formHeader.config.title);

          if (this.oauthError) {
            this.toggleFooterDisable(true);
          }

          const formmodeId = res.formmodeId;
          if (formmodeId) {
            this.joinCube.formmodeId = formmodeId;
            this.joinCube.isSetCategory = res.isSetCategory;
          }

          this.setEdcForm();

          resolve();
        }
        ).catch((res) => {
          this.error = res;
          this.isInit = false;
        });
      }).catch(error => {
        this.initClientLanguage(false);
        this.error = error;
        this.isInit = false;
      });
    });
  })

  singleSignOn = () => {
    if (!this.oauthKey && (isWXWork() || isDingTalk())) {
      return new Promise((resolve) => {
        fillin.fakeSSO().then((res) => {
          if (res.redirect && res.emOpenUrl) {
            const now = new Date().getTime();
            const emLastRedirect = sessionStorage.getItem("edc_em_last_redirect");
            if (!emLastRedirect || now - emLastRedirect > 1000 * 60) {
              sessionStorage.setItem("edc_em_last_redirect", now);
              window.location.href = res.emOpenUrl + '/wxapi/wxclienturl/redirect?em_sys_id='
                + res.ecId + '&redirect_url=' + encodeURIComponent(window.location.pathname + (window.location.search || ""));
              return;
            }
          }
          resolve();
        });
      }, () => {
        resolve();
      }).catch(() => {
        resolve();
      });
    }
    return Promise.resolve();
  }

  triggerAllFieldRules = () => {
    // 处理页面上所有组件字段符合规则的情况，若组件不可见，不触发规则
    if (this.rules && this.rules.length) {
      this.components.filter(com => com.value)
        .forEach(com => com.visible && this.triggerRules(com, com.value));
      this.components = toJS(this.components);
    }
  }

  setEdcForm = () => {
    window.EdcForm = new EdcForm(this);
    this.initEdcCode();
    EE.emit(DOMLOAD);
  }

  initEdcCode = () => {
    const { JS, CSS } = this.codeBlock;

    if (JS) {
      const script = '<script type="text/javascript">' + JS + '</script>';

      jQuery(document.body).append(script);
    }

    if (CSS) {
      const style = '<style type="text/css">' + CSS + '</style>';

      jQuery(document.head).append(style);
    }
  }

  setComponents = (components) => this.components = toJS(components);

  @action initReadOnly = (shortkey, data) => {
    if (!shortkey || this.shortkey) return;
    if (!data) return;

    this.shortkey = shortkey;
    this.theme = getTheme('default');
    const { authorization_str = '' } = getPageUrlParams();

    fillin.check(shortkey, this.oauthKey).then(res => {
      this.isInit = true;

      this.code = res.code;
      this.appid = res.appid || '';
      this.rightLevel = res.rightLevel;
      this.isOAUser = res.isOAUser;
      this.viewType = viewTypes.READONLY;
      this.isShowRepairTitle = res.makeUp;

      Promise.all([
        fillin.getDataInfo(shortkey, data, authorization_str),
        fillin.getRules(shortkey),
        this.thridPartyInit().then(() => this.initClientLanguage(res.isOAUser)),
      ]).then(([res, rules]) => {
        const coms = res.comps;

        this.readOnlyBaseData = res.baseData;
        if (res.style) {
          const style = JSON.parse(res.style);
          style && (this.theme = style);
          const background = style.background;
          if (background && background.type == 0) {
            this.addbgStyle(background.css);
          }
        }

        const components = this.convertToViewComponent(coms);
        const comMaps = {};

        components.forEach(com => {
          comMaps[com.uuid] = com;
        });

        const _rules = type => rules.filter(r => type === r.type);
        this.rules = _rules(FIELD)
        this.formHeader = coms.find(com => com.type === FORM_HEADER);
        this.formFooter = coms.find(com => com.type === FORM_FOOTER);
        this.footer = coms.find(com => com.type === FOOTER);

        this.rules.forEach(({ target }) => {
          target.split(',').forEach(tId => {
            const com = this.getComponent(tId, components);
            com.visible = false;
          });
        });

        this.components = components.filter(com => {
          if (!com.pid) return true;

          return !isDataTable(comMaps[com.pid]);
        });
        document.title = this.formHeader.config.title;

        this.editData = res.data;

        const formmodeId = res.formmodeId;
        if (formmodeId) {
          this.joinCube.formmodeId = formmodeId;
        }
        this.handleReadOnly();
        this.isInit = false;
      }).catch((res) => {
        this.error = res;
        this.isInit = false;
      });
    }).catch(error => {
      this.error = error;
      this.isInit = false;
    });
  }

  convertToViewComponent (coms) {
    coms = coms.filter(isNormal);

    coms.filter(isWrapper).forEach(com => {
      com.config.coms = com.config.coms.map(subComId => {
        return coms.find(({ uuid }) => uuid === subComId);
      });
    });

    return coms.map(propsComToViewCom);
  }

  @action initOauthKey = code => {
    if (!code || this.oauthKey) return;

    this.oauthError = null;
    const oauthKey = localStorage.getItem(code);
    if (oauthKey) {
      this.oauthKey = oauthKey;
    } else {
      localStorage.clear();
      return fillin.genOauthKey(code).then((res) => {
        if (res) {
          localStorage.setItem(code, res);
          this.oauthKey = res;
        } else {
          this.oauthError = 'error oauth';
        }
      }).catch(error => {
        this.oauthError = error || 'error';
      });
    }
  }

  addbgStyle (css) {
    let cssRule = `.wea-edc-fv-wrapper-mobilebg:before {
      content: '';
      position: fixed;
      top: 0;
      height: 100vh;
      width: 100vw;
      left: 0;
      background: ${css.backgroundImage} center 0 ${css.backgroundRepeat};
      background-size: ${css.backgroundSize};
    }`;
    let styleElement = document.getElementById('styles_mobilebg');

    if (!styleElement) {
      styleElement = document.createElement('style');
      styleElement.type = 'text/css';
      styleElement.id = 'styles_mobilebg';
      document.getElementsByTagName('head')[0].appendChild(styleElement);
    }
    styleElement.appendChild(document.createTextNode(cssRule));
  }


  //多条跳转规则存在时, 取最后一个组件的跳转路径
  getJumpUrl (coms) {
    const jumpRule = this.jumpRule.filter(rule => {
      let result = false;

      coms.forEach(com => {
        if (rule.trigger === com.uuid && com.value.length) {
          com.value.forEach(val => {
            if (rule.option === val.key) {
              result = true;
            }
          });
        }
      });
      return result;
    });

    const _index = uuid => this.components.findIndex(com => uuid === com.uuid);
    // 处理 sort方法浏览器兼容问题
    const bubbleSort = arr => {
      let len = arr.length - 1;
      for (let j = 0; j < len; j++) {
        for (let i = 0; i < len - j; i++) {
          if (arr[i].compareValue >= arr[i + 1].compareValue) {
            [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
          }
        }
      }
    }

    const newJumpRule = jumpRule.map(r => {
      const i = _index(r.trigger);
      r.compareValue = i;

      return r;
    });

    bubbleSort(newJumpRule);

    if (newJumpRule.length) return newJumpRule[0].target;

    return '';
  }

  @action onValueChange = (uuid, value) => {
    const com = this.getComponent(uuid);

    if (_.isEqual(toJS(com.value), value)) return;

    com.value = value;

    const { valid, errorCom } = this.isFormValid([com]);

    if (!valid) this.errorCom = errorCom;

    this.onValueChangeByCode(uuid, value);
    this.triggerRules(com, value);
    this.clearError(com, this.getComponent(com.pid));
    this.components = toJS(this.components);
  }

  onValueChangeByCode = (uuid, value) => {
    const evtName = FIELDVALUECHANGE + '_' + uuid;

    EE.emit(evtName, uuid, value);
  }

  triggerRules (triggerCom, value) {
    if (!isOptional(triggerCom)) return;

    const allTargetComs = []; // 所有符合规则的target com
    const values = value && value.map(v => v.key) || [];
    const rules = this.rules.filter(r => {
      return triggerCom.uuid === r.trigger;
    }).map(({ option, target }) => {
      const targets = target.split(',');
      const coms = targets.map(tId => this.getComponent(tId));

      allTargetComs.push(...coms);

      return { coms, option };
    });

    // 重置target的visible
    allTargetComs.forEach(com => {
      com.visible = false;
      this.onChildVisibleChange(com);
    });

    rules.forEach(({ option, coms }) => {
      coms.forEach(com => {
        // 防止多条规则作用于同一个字段时，字段显示值被多次覆盖
        // 如A,B规则都需要显示字段C，不return则会出现visible被覆盖的问题
        if (!com.visible) {
          com.visible = values.includes(option);
          // 再次使用规则
          this.triggerRules(com, com.visible && com.value);
        }

        this.onChildVisibleChange(com);
      });
    });
  }

  onChildVisibleChange = com => {
    com.config.complex && this.components.forEach(childCom => {
      if (com.uuid === childCom.pid) {
        childCom.visible = com.visible;
      }
    });
  }

  getComponent (uuid, coms) {
    if (!uuid) return null;

    return (coms || this.components).find(com => uuid === com.uuid);
  }

  @action onSubmit = (isLimitTime) => {
    if (this.submiting) return;

    let valid = true;
    let errorCom = null;

    if (!isLimitTime) {
      const { valid: v, errorCom: ec } = this.isFormValid();
      valid = v;
      errorCom = ec;
    }

    if (isLimitTime || (valid && !isLimitTime)) {
      const coms = this.getComs();
      const _toggleLoading = isLoading => {
        this.formFooter.loading = isLoading;
        this.formFooter = toJS(this.formFooter);
        this.submiting = isLoading;
      };

      _toggleLoading(true);

      const jumpUrl = this.getJumpUrl(coms);
      const formdata = this.getFormData(coms);

      emit(ONBEFORESUBMIT).then(res => {
        if (res === false) {
          return _toggleLoading(false);
        }

        const makeUpDate = this.repairDate ? this.repairDate : "";

        fillin.submit({ ...formdata, autoSave: isLimitTime || false, makeUpDate }).then((res) => {
          if (this.rightLevel > 0) { // 在有查看权限时，会去重新请求收集结果
            this.getSubmitCount();
          }
          if (jumpUrl) {
            return window.open(jumpUrl, "_self");
          }

          EE.emit(ONSUBMIT, res.id);
          this.submiting = false;
          this.success = true;

          const isemobile = isEMobile7();

          if (isemobile) {
            const emUrl = this.emOpenUrl + '/open/js/jem.js?v=' + new Date().getTime();

            let name = '';
            const { registerSign } = getPageUrlParams();

            if (registerSign) {
              name = `edcMobileFill_${registerSign}`;
            }

            loadjs(emUrl, () => {
              em.postBroadcast({
                'name': name,
                'text': ''
              });
            })

          }

          if (makeUpDate) {
            this.repairDate = '';
            this.isShowRepairTitle = false;
            fillin.getMakeUpDate(this.shortkey).then(res => {
              const dates = res.dates;
              if (dates && dates.length > 0) {
                this.isShowRepairTitle = true;
              }
            });
          }
        }).catch(() => {
          _toggleLoading(false);
        });
      });
    } else {
      this.components = toJS(this.components);
      this.errorCom = errorCom;
    }
  }

  @action toggleFooterDisable = (disable) => {
    this.formFooter.disable = disable;
    this.formFooter = toJS(this.formFooter);
    this.submiting = disable;
  }

  @action resetErrorCom = () => {
    this.errorCom = null;
  }

  @action handleEdit = () => {
    const { editData, components } = this;

    const setComVal = com => {
      const uuid = com.uuid;
      const val = editData[uuid] && editData[uuid] || '';
      val && (com.value = val);
      return val;
    };

    components.forEach(com => {
      if (isAddress(com)) {
        const { province, city, district, detail } = com.config;
        com.value = setComVal(province) + setComVal(city) + setComVal(district) + setComVal(detail);
      } else {
        const uuid = com.uuid;
        if (uuid in editData) {
          com.value = editData[uuid];
        }
      }
    });

    this.components = toJS(components);
    this.triggerAllFieldRules();
    this.editConfirm = false;
    this.isEdit = true;
  }

  @action handleNew = () => {
    this.isEdit = false;
    this.editConfirm = false;
    this.success = false;
  }

  @action handleReadOnly = () => {
    this.viewType = READONLY;
    this.handleEdit();
  }

  thridPartyInit () {
    const thirdParty = new ThirdParty(this.shortkey);

    return thirdParty.init().then(res => {
      if (res === 'wx' || res === 'wxWork') {
        this.viewType = MOBILE_WX;
      }
    });
  }

  isFormValid (components) {
    const coms = components || this.components.filter(needValid);

    let errorCom = coms.find(com => {

      return !this.isComValid(com);
    });

    if (errorCom && errorCom.pid) {
      const parentCom = this.getComponent(errorCom.pid);

      if (!isLayout(parentCom)) {
        parentCom.errorCom = errorCom;
        errorCom = parentCom;
      } else {
        const { coms } = parentCom.config;
        const subComIndex = coms.findIndex(c => c && c.uuid === errorCom.uuid);

        parentCom.config.coms[subComIndex] = errorCom;
      }
    }

    return {
      errorCom,
      valid: !errorCom,
    };
  }

  isComValid (com) {
    com.valid = true;
    com.error = '';

    com.rules.every(rule => {
      const { error, valid } = this.validate(rule, com);

      if (valid) return true;

      com.valid = false;
      com.error = error;
    });

    return com.valid;
  }

  validate (rule, field) {
    const valid = rule.validate(field);
    const error = !valid ? rule.error(field) : '';

    return { valid, error };
  }

  clearError (subCom, complexCom) {
    const hasNoError = !subCom.error && (complexCom && !complexCom.errorCom);

    if (hasNoError) return;

    if (isMobileCom(subCom)) {
      this.isComValid(subCom);
    } else {
      subCom.error = '';

      if (complexCom) {
        complexCom.error = '';

        if (isDataTable(complexCom)) {
          complexCom.config.errors = [];
        }

        if (isAddress(complexCom) && complexCom.errorCom) {
          complexCom.errorCom.error = '';
        }
      }

      if (isDataTable(subCom)) {
        subCom.config.errors = [];
      }
    }
  }

  getFormData (coms) {
    const { oauthKey } = this;
    const { edc_field, conversationId, conversationType } = getPageUrlParams();
    let data = {};

    oauthKey && (data.oauthKey = oauthKey);
    data.key = this.shortkey;
    data.datas = JSON.stringify(coms);
    this.isEdit && (data.isEdit = true);
    edc_field && (data.extendData = edc_field);

    if (conversationType && conversationId) { // 当前会话传参，用于填写消息回执
      data.conversationType = conversationType;
      data.conversationId = conversationId;
    }
    return data;
  }

  _getCom (com) {
    let { uuid, value } = com;
    let smsCode = '';

    if ((isAttachment(com) || isPicture(com)) && value) {
      let docIds = [];
      value.forEach(({ docid }) => {
        docid > 0 && (docIds.push(docid));
      });
      value = docIds.join(',');
    }

    if (isSignature(com) && value) {
      value.docid && (value = value.docid);
    }

    if (!isVisible(com) && !this.isEdit) {
      com.config && (value = com.config.defaultValue);
    }

    if (isMobileCom(com) && parseInt(com.config.smsVerification)) { // 如果是手机类型，获取验证码codeValue
      smsCode = com.config.codeValue || '';
      return { uuid, value, smsCode };
    }

    return { uuid, value };
  }

  getComs () {
    return this.components.filter(needValid).map((com) => {

      if (isDataTable(com)) {
        const { uuid, value, config: { coms } } = com;

        const newValue = value.map((rowValues, rowIndex) => {
          return rowValues.map((v, colIndex) => {
            const childCom = this._getCom({ ...coms[colIndex], value: v });

            if (isMobileCom(coms[colIndex])) {
              return childCom;
            }

            return childCom.value;
          });
        });

        return { uuid, value: newValue };
      }

      return this._getCom(com);
    });
  }

  initClientLanguage (isOAUser) {
    return new Promise(resolve => {
      if (isOAUser) {
        WeaLocaleProvider.getLocaleLabel('edc', '', '', resolve);
      } else {
        this.getActiveLanguage().then(() => {
          this.initLanguageId().then(res => {
            this.setClientLanguage(res).then(resolve);
          });
        });
      }
    }).then(() => {
      return new Promise(res => {
        const lang = getUserLanguage();

        // 无法拿到语言时，默认使用中文语言环境
        if (!lang) {
          this.setClientLanguage('7').then(res);
        } else {
          res();
        }
      });
    });
  }

  getActiveLanguage = () => {
    return new Promise(resolve => {
      WeaTools.callApi(
        "/api/system/language/base/getActiveLanguage",
        "GET"
      ).then(res => {
        if (res) {
          this.systemDefaultLang = res;
        }
        resolve();
      });
    });
  }

  initLanguageId = emOpenUrl => {
    return new Promise(resolve => {
      const browserInfo = toJS(this.browserInfo);
      const isemobile = isEMobile7();
      let languageId = '';
      let isSetting = false;

      // 是否设置多语言类型
      const tempStr = 'languageId=';
      const index = browserInfo.href.indexOf(tempStr);
      let Idstr = '';
      let Id = null;
      if (index > -1) {
        Idstr = browserInfo.href.substr(tempStr.length + index, 2);
      }
      Id = Idstr.match(/\d+/g);

      if (Id) {
        isSetting = this.systemDefaultLang.activeLanguageIds.some(r => r === Id[0]);
      }

      const transformLang = bl => {
        const newBl = bl.toLowerCase();
        const langType = langTypes[newBl] || langTypes['default'];

        return langType;
      }

      if (isemobile) {
        const thirdParty = new ThirdParty();

        thirdParty.excu("getLanguage").then((clientLang) => {
          resolve(transformLang(clientLang));
        }).catch(() => {
          resolve(transformLang('zh'));
        });
      } else if (isSetting) {
        languageId = Id[0];
        resolve(languageId);
      } else {
        languageId = transformLang(browserInfo.browserLanguage);
        resolve(languageId);
      }
    });
  }

  setClientLanguage = languageId => {
    return new Promise(res => {
      const data = { langId: languageId };
      const login = JSON.stringify(data);

      // 公共组件getLocaleLabelByLang方法中需要该缓存
      window.localStorage.setItem('login', login);
      getLocaleLabelByLang(['COMMON', 'EDC'], languageId).then(res);
    });
  }

  @action getSubmitCount = () => {
    const { statisticsMode, data } = getPageUrlParams();

    if (this.appid && this.rightLevel > 0 && (Number(statisticsMode) === 1 || data)) {
      Promise.all([
        app.getSubmitCount(this.appid),
        app.getBaseInfo(this.appid)
      ]).then(([res, data]) => {
        this.submitCount = res;
        this.fillinEnable = data.fillinEnable;
      });
    }
  }

  @action toggleRepairList = (isShowRepairList) => this.isShowRepairList = isShowRepairList;

  @action closeRepairTitle = () => this.isShowRepairTitle = false;

  @action setRepairDate = date => {
    this.repairDate = date;
    if (this.viewType == READONLY) {
      this.components = [];
      this.init(this.shortkey);
    }
  }
}